package com.base.leetcode;

/**
 * @Author: hdhao
 * @Create: 2023/3/30 - 19:46
 * @Version: v1.0
 */
//删除有序链表重复节点(重复元素保留一个)
public class Leetcode83 {

    public static void main(String[] args) {
        ListNode o5 = new ListNode(6, null);
        ListNode o4 = new ListNode(3, o5);
        ListNode o3 = new ListNode(2, o4);
        ListNode o2 = new ListNode(2, o3);
        ListNode o1 = new ListNode(1, o2);

        System.out.println(o1);
        ListNode listNode = deleteDuplicates(o1);
        System.out.println(listNode);
    }

    //方法1
    public static ListNode deleteDuplicates(ListNode head){
        //节点数<2
        if (head == null || head.next == null){
            return head;
        }
        //当节点数>2
        ListNode p1 = head;
        ListNode p2;
        while ((p2=p1.next)!=null){
            if (p1.val == p2.val){
                //删除p2
                p1.next = p2.next;
            }else {
                //向后平移
                p1 = p1.next;
            }
        }
        return head;
    }

    //方法2
    public static ListNode deleteDuplicates2(ListNode p){
        if (p == null || p.next == null){
            return p;
        }
        if (p.val == p.next.val){
            return deleteDuplicates2(p.next);
        }else {
            p.next =deleteDuplicates2(p.next);
            return p;
        }
    }
}
